import axios from "axios";
import router from "../../router";

const instance = axios.create({
  // `withCredentials` Access-Control-Allow-Credentials 响应头表示是否可以将对请求的响应暴露给页面
  withCredentials: true,
  timeout: 2000,
  baseURL: "http://localhost:8888/api",
});

instance.defaults.headers.common = {};
instance.defaults.headers.post = {
  "Content-Type": "application/json",
};
instance.interceptors.request.use(
  (config) => {
    if (localStorage.getItem("token ")) {
      let token = `Bearer ${localStorage.getItem("token ")}`;
      //Authorization
      // config.headers.Authorization = token;
      config.headers!.Authorization = token;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

instance.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    // token过期了
    const { status } = error.response;
    if (status == 401) {
      //后台定义401为token过期
      alert("token过期,请重新登录!");
      localStorage.removeItem("token ");
      //   清楚后让它跳转到登录页面去
      router.push("/login");
    } else {
      alert(error.response.data);
    }
    return Promise.reject(error);
  }
);

export default instance;
